package com.leectrl.utils;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;

public class Bus {
    private Map<String, CopyOnWriteArrayList<MessageEvent>> listener = new HashMap<String, CopyOnWriteArrayList<MessageEvent>>();
    private static Bus bus;
    private Bus() {

    }

    public static Bus getInstance() {
        if (bus == null) {
            bus = new Bus();
        }
        return bus;
    }

    public void emit(String key, Object... message) {
        if (key == null) {
            throw new NullPointerException();
        }
        if (listener.containsKey(key)) {
            CopyOnWriteArrayList<MessageEvent> messageEvents = listener.get(key);

            synchronized (messageEvents) {
                for (MessageEvent messageEvent : messageEvents) {
                    messageEvent.onEvent(key, message);
                }
            }
        }
    }

    public void once(String key, MessageEvent messageEvent) {
        if (key == null) {
            throw new NullPointerException();
        }
        if (!listener.containsKey(key)) {
            CopyOnWriteArrayList<MessageEvent> messageEvents = new CopyOnWriteArrayList<MessageEvent>();
            messageEvents.add(messageEvent);
            listener.put(key, messageEvents);
        }

    }

    public void on(String key, MessageEvent messageEvent) {
        if (key == null) {
            throw new NullPointerException();
        }
        if (listener.containsKey(key)) {
            listener.get(key).add(messageEvent);
        } else {
            CopyOnWriteArrayList<MessageEvent> messageEvents = new CopyOnWriteArrayList<MessageEvent>();
            messageEvents.add(messageEvent);
            listener.put(key, messageEvents);
        }
    }

    public void off(String key) {
//        if (key == null) {
//            throw new NullPointerException();
//        }
//        synchronized (listener) {
//            if (listener.containsKey(key)) {
//                listener.remove(key);
//            }
//        }
    }

    public interface MessageEvent {
        public void onEvent(String key, Object... message);
    }
}
